﻿// FILE           :Server.cs
// PROJECT        :SETCritters                                        
// PROGRAMMER     :Kenneth Jinks and Ryan Pink                                         
// FIRST VERSION  :Sept 11 2013                                                
// DESCRIPTION    :
//      This file contains the main server class, which listens on the port for incoming
//      requests. When the server receives a request, it sends the client information
//      to ClientHandler for processing via a thread.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace TheServer
{
    /// <summary>
    /// The server class uses the websocket protocol to communicate with the client.
    /// This has been referenced from 
    /// https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_server
    /// </summary>
    class Server
    {

        TcpListener serverListener;

        /// <summary>
        /// Destructor ensures server is closed
        /// </summary>
        ~Server()
        {
            serverListener.Server.Close();
        }

        /// <summary>
        /// Server - Default Constructor
        /// </summary>
        /// <param name="port">Port the connection is coming from</param>
        public Server(int port)
        {
            serverListener = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
            serverListener.Start();

            Console.WriteLine("Server has begun listening on port " + port.ToString() + Environment.NewLine);
        }

        /// <summary>
        /// WaitForClientconnect - Server waits on this function for a connection request
        /// </summary>
        /// <param name="client">TCP client connection</param>
        public void WaitForClientConnect(ref TcpClient client)
        {
            client = serverListener.AcceptTcpClient();

            Console.WriteLine("Client connected", Environment.NewLine);
            ClientHandler clientHandler = new ClientHandler();

            //database reference should be passed to the client at this point
            //so that the client will have access to the database
            clientHandler.StartClient(ref client);
        }
    }
}
